package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.entity.Comment;
import com.example.mapper.CommentMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentService {

    @Resource
    private CommentMapper commentMapper;

    public PageInfo selectPage(Comment comment, Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> comments = commentMapper.selectAll(comment);
        List<Comment> replies = commentMapper.selectReply(comment);
        List<Comment> list = new ArrayList<>();
        for(Comment rootComment : comments){
            for(Comment reply : replies){
                if(reply.getPid().equals(rootComment.getId())){
                    list.add(reply);
                }
            }
            rootComment.setChildren(list);
            list = new ArrayList<>();
        }
        return PageInfo.of(comments);
    }

    public void delete(Integer id){
        commentMapper.deleteById(id);
    }

    public void deleteByFilmId(Integer id){
        commentMapper.deleteByFilmId(id);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            commentMapper.deleteById(id);
        }
    }

    public void add(Comment comment){
        comment.setTime(DateUtil.now());
        commentMapper.insert(comment);
    }

    // 查询不同评论数量
    public List<Comment> countComment(Integer id){
        return commentMapper.countComment(id);
    }
}
